package com.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import com.data.Common;

import java.util.ArrayList;
import java.util.List;

/**
 * X轴
 * Created by White
 * Email：whitelaning@qq.com
 */

public class AxisXView extends View {
    private float xPoint = 0;// 原点X坐标
    private float yPoint = 0;// 原点Y坐标
    private float xLength = 0;// X轴长度
    private float yLength = 0;// Y轴长度

    private List<String> xLabelList = new ArrayList<>();// X轴标签

    private Paint mPaint = new Paint();
    private Rect mRect = new Rect();

    private int count = 1;//每多少个刻度显示一次文本
    private int xScaleEachLength = 0;//每格的长度

    private int xBoundaryValue = 5;//防止布局和边界重叠而显示不全
    private int xScaleLabelOffset = 30;//文字和轴线的偏移量
    private int xStrokeWidth = 2;//画笔宽度

    public AxisXView(Context context) {
        super(context);
    }

    public void initValue(float Width, float Height) {
        xLength = Width;
        yLength = Height;

        xLabelList = Common.xScaleArrayLabel;
        xScaleEachLength = Common.xScaleEachLength;
        xBoundaryValue = Common.xBoundaryValue;

        initPaint();
    }

    private void initPaint() {
        // 设置画笔
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);// 设置画笔样式
        mPaint.setAntiAlias(true);// 去锯齿
        mPaint.setColor(Common.xScaleColor);// 设置颜色
        mPaint.setTextSize(25);// 设置字体
        mPaint.setStrokeWidth(xStrokeWidth);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 画X轴轴线

        canvas.drawLine(xPoint, yPoint + xStrokeWidth / 2, xPoint + xLength, yPoint + xStrokeWidth / 2, mPaint);

        // 画X轴刻度和文字
        for (int i = 0; xLabelList != null && i < xLabelList.size(); i++) {
            if (i % count == 0) {
                //绘制文字
                mPaint.getTextBounds(xLabelList.get(i), 0, xLabelList.get(i).length(), mRect);
                int width = mRect.width();//文本的宽度
                int height = mRect.height();//文本的高度

                canvas.drawText(xLabelList.get(i), xPoint + xScaleEachLength * i - width / 2, yPoint + height + xScaleLabelOffset + xBoundaryValue, mPaint);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension((int) xLength, (int) yLength);
    }
}
